// pages/shopcar/shopcar.js
const app = getApp();
import api from '../../api/index.js';
const {request} = require('../../utils/wx-api.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShow: true,
    hasGoods: false,
    cartList: '',
    cartTotal: '',
    totalPrice: 0,
    totalNum: 0,
    selectAllStatus: 1,
    isEdit:false
  },
  getCartData() { //获取购物车数据
    // console.log("获取")
    request({ url: api.cartData }, {}, "GET", {'X-Nideshop-Token': app.globalData.token})
      .then(res => {
        // console.log(res);
        let cartTotal = res.data.data.cartTotal;
        if (cartTotal.goodsCount != 0) {
          this.setData({
            hasGoods: true,
            cartList: res.data.data.cartList,
            cartTotal: cartTotal
          })
          let cartList = this.data.cartList;
          for (let i = 0; i < cartList.length; i++) {
            if (cartList[i].checked) {
              this.setData({
                selectAllStatus: 1
              })
            } else {
              this.setData({
                selectAllStatus: 0
              })
              break
            }
          }
        }
        this.getTotalPrice();
      })
  },
  updateCart(id, goodsId, number, productId) { //更新购物车数据
    request({url: api.cartUpdate}, {
        id: id,
        goodsId: goodsId,
        number: number,
        productId: productId
      }, "POST",{'X-Nideshop-Token': app.globalData.token})
      .then(res => {
        console.log("update", res);
        // this.setData({
        //   cartList: res.data.data.cartList
        // })
      })
  },
  checkedCart(productId,isChecked){  //选择获取取消选择商品
    request({url:api.cartChecked},{
      productIds: productId,
      isChecked: isChecked
    },'POST',{'X-Nideshop-Token': app.globalData.token})
    .then(res=>{
      // console.log('checked',res);
      if(typeof(productId)=='string') {
        this.setData({
          cartList: res.data.data.cartList
        });
        this.getTotalPrice();
      }
    })
  },
  getTotalPrice() { //计算总价和总量
    let cartList = this.data.cartList;
    let total = 0;
    let totalNum = 0;
    for (let i = 0; i < cartList.length; i++) {
      if (cartList[i].checked) {
        //已选的商品总价
        total += cartList[i].number * cartList[i].retail_price;
        //已选的商品总量
        totalNum += cartList[i].number;
      }
    }
    // debugger
    this.setData({
      totalPrice: total.toFixed(2),
      totalNum
    })
  },
  editCart(e) { //编辑购物车（删除）
    let isEdit = !this.data.isEdit;
    this.setData({
      isEdit
    })
  },
  delGoods(){ //删除购物车商品
    let cartList = this.data.cartList;
    let productIdArr = [];
    for(let i=0;i<cartList.length;i++){
      if(cartList[i].checked){
        productIdArr.push(cartList[i].product_id);
      }
    }
    let productId = productIdArr.join();
    request({url:api.cartDelete},{
      productIds: productId
    },"POST",{'X-Nideshop-Token': app.globalData.token})
    .then(res=>{
      console.log("delete",res);
      this.setData({
        cartList:res.data.data.cartList
      })
      if (!res.data.data.cartList.length) {
        this.setData({
          hasGoods: false,
          isEdit:false
        })
      }
    })
    console.log(productIdArr);
  },
  selectList(e) { //选择商品
    let index = e.currentTarget.dataset.index;
    let cartList = this.data.cartList;
    let checked = cartList[index].checked;
    // cartList[index].checked = Number(!checked);
    //只修改当前这一个对象
    let jsonStr = `{"cartList[${index}].checked":${Number(!checked)}}`;
    this.setData(JSON.parse(jsonStr));
    //获取当前项
    let item = cartList[index];
    //更新数据
    this.checkedCart(item.product_id, item.checked);
    // console.log(JSON.parse(jsonStr));
    for (let i = 0; i < cartList.length; i++) {
      if (cartList[i].checked) {
        this.setData({
          selectAllStatus: 1
        })
      } else {
        this.setData({
          selectAllStatus: 0
        })
        break
      }
    }
    this.getTotalPrice();
  },
  selectAll() { //全选
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = Number(!selectAllStatus);
    let cartList = this.data.cartList;
    let productIdArr = [];
    for (let i = 0; i < cartList.length; i++) {
      //获取每一项的productId存在一个数组里
      productIdArr.push(cartList[i].product_id);
    }
    //将数组转为字符串进行传参
    let productId = productIdArr.join();
    //更新数据
    this.checkedCart(productId, selectAllStatus);
    this.setData({
      selectAllStatus
    })
  },
  minusCount(e) { //减少数量
    let index = e.currentTarget.dataset.index;
    let cartList = this.data.cartList;
    let num = cartList[index].number;
    if (num <= 0) {
      return false
    }
    num--;
    // cartList[index].number = num;
    //只修改当前项
    let jsonStr = `{"cartList[${index}].number":${num}}`;
    this.setData(JSON.parse(jsonStr));
    //获取当前项
    let item = cartList[index];
    //更新数据
    this.updateCart(item.id, item.goods_id, item.number, item.product_id);
    this.getTotalPrice();
  },
  addCount(e) { //增加数量
    let index = e.currentTarget.dataset.index;
    let cartList = this.data.cartList;
    let num = cartList[index].number;
    if (num >= 99) {
      return false
    }
    num++;
    // cartList[index].number = num;
    //只修改当前项
    let jsonStr = `{"cartList[${index}].number":${num}}`;
    this.setData(JSON.parse(jsonStr));
    //获取当前项
    let item = cartList[index];
    //更新数据
    this.updateCart(item.id, item.goods_id, item.number, item.product_id);
    this.getTotalPrice();
  },
  bindinput(e) { //输入框修改数量
    let index = e.currentTarget.dataset.index;
    let cartList = this.data.cartList;
    let num = Number(e.detail.value);
    if (num > 99) {
      return
    }
    // cartList[index].number = num;
    //只修改当前项
    let jsonStr = `{"cartList[${index}].number":${num}}`
    //获取当前项
    let item = cartList[index];
    //更新数据
    this.updateCart(item.id, item.goods_id, item.number, item.product_id);
    this.setData(JSON.parse(jsonStr));
    this.getTotalPrice();
  },
  buy(){  //下单
    if (this.data.totalPrice==0){
      return false
    }
    if (!app.globalData.addressId) {
      wx.navigateTo({
        url: '../addressManage/addressManage'
      })
    } else {//已登录并且获取到地址信息，即可提交订单
      let { addressId } = app.globalData;
      wx.navigateTo({
        url: `../orderCheckout/orderCheckout?addressId=${addressId}`
      })
    }
  },
  bindgetuserinfo(res) {//购物车登录
    // console.log(res);
    if (res.detail.errMsg.indexOf('fail') != -1) {
      //说明用户拒绝授权
      //请授权，否则相关功能不可用
      wx.showToast({
        icon: 'none',
        title: '请授权，否则相关功能不可用',
        duration: 3000
      })
    } else {
      let userInfoDetail = res.detail;
      let {userInfo} = res.detail;
      var that = this;
      wx.login({
        success: function(result) {
          // console.log('code',result);
          request({
              url: api.loginByWeixin
            }, {
              appId: 'wxfa48bdefa8725047',
              secret: '00d987a912597db6c7651655bf722452',
              code: result.code,
              userInfo: userInfoDetail
            }, "POST")
            .then(res => {
              // console.log(res);
              if (res.data.errmsg) {
                wx.showModal({
                  title: '提示',
                  content: '登录失败'
                })
              } else {
                app.globalData.userInfo = userInfo;
                wx.setStorageSync('token', res.data.data.token);
                app.globalData.token = wx.getStorageSync('token');
                // console.log("token", app.globalData.token);
                that.setData({
                  isShow: false
                });
                that.getCartData();
              }
            })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // console.log(app);
    if (app.globalData.token) {
      this.setData({
        isShow: false
      });
      this.getCartData();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})